import React from "react";
import { connect } from "react-redux";
import { Dispatch } from "redux";
import { rootState } from "./store";
import { IAdmin, IAdminActionType } from "./store/reducers/admin";
import { IUser, IUserActionType } from "./store/reducers/user";
interface IProps {
  admin?: IAdmin;
  user?: IUser;
  changeAdminName?(): void;
  changeUserName?(): void;
}

const RFCExample: React.FC<IProps> = (props: IProps) => {
  console.log(props);
  const changeUserName = () => {
    props.changeUserName && props.changeUserName();
  };
  const changeAdminName = () => {
    props.changeAdminName && props.changeAdminName();
  };

  return (
    <div>
      <h1>函数式组件使用redux</h1>
      {props.admin?.name}
      <br />
      {props.user?.name}
      <br />
      <button onClick={changeAdminName}>change admin name</button>
      <button onClick={changeUserName}>change user name</button>
      <br />
    </div>
  );
};

// 第一步把store 映射到props上
const mapStateToProps = (state: rootState) => {
  return { ...state.admin, ...state.user };
};
// 第二步修改store的值,方法映射到props上
const mapDispatchToProps = (dispatch: Dispatch) => ({
  changeAdminName: () => {
    dispatch({
      type: IAdminActionType.CHANGE,
      payload: {
        admin: {
          name: "change Admin YUSIR",
        },
      },
    });
  },
  changeUserName: () => {
    dispatch({
      type: IUserActionType.CHANGE,
      payload: {
        user: {
          name: "change user YUSIR",
        },
      },
    });
  },
});
export default connect(mapStateToProps, mapDispatchToProps)(RFCExample);
